package com.yiqi.lottery.feature.basketball.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.suozhang.framework.entity.bo.PageData;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.yiqi.lottery.R;
import com.yiqi.lottery.common.util.DataManager;
import com.yiqi.lottery.entity.bo.BallMatchBo;
import com.yiqi.lottery.entity.bo.BallMatchBo2;
import com.yiqi.lottery.feature.basketball.adapter.BasketballMatchAdapter;
import com.yiqi.lottery.feature.basketball.contract.BasketballContract;
import com.yiqi.lottery.feature.basketball.dependencies.basketball.BasketballPresenterModule;
import com.yiqi.lottery.feature.basketball.dependencies.basketball.DaggerBasketballComponent;
import com.yiqi.lottery.feature.football.view.MatchFilterActivity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class BasketballMatchBetActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener, BasketballContract.View {

    @BindView(R.id.view_toolbar)
    RelativeLayout view_toolbar;
    @BindView(R.id.img_back)
    ImageView img_back;
    @BindView(R.id.ll_center)
    LinearLayout ll_center;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_xiala)
    ImageView img_xiala;
    @BindView(R.id.img_shaixuan)
    ImageView img_shaixuan;
    @BindView(R.id.list_view)
    ExpandableListView list_view;
    @BindView(R.id.img_delete)
    ImageView img_delete;
    @BindView(R.id.tv_selected)
    TextView tv_selected;
    @BindView(R.id.tv_buy)
    TextView tv_buy;

    BasketballMatchAdapter mAdapter;
    PopupWindow mPopupWindow;
    private int mCurrentBetType;

    private ArrayList<BallMatchBo> mDataList;

    private ArrayList<String> mMatchFilters;

    @Inject
    BasketballContract.Presenter mPresenter;

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return false;
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_football_match_bet;
    }

    @Override
    protected void initView() {
        mCurrentBetType = 4;
        tv_title.setText("混合过关");
        initExpandableListView();
    }

    private void initExpandableListView() {
        list_view.setGroupIndicator(null);
        list_view.setAdapter(getAdapter());
    }

    private BasketballMatchAdapter getAdapter() {
        if (mAdapter == null) {
            mAdapter = new BasketballMatchAdapter(this);
            mAdapter.setOnCheckedNumChangeListener(new BasketballMatchAdapter.OnCheckedNumChangeListener() {
                @Override
                public void onCheckedNumChange(int num) {
                    tv_selected.setText(Html.fromHtml("已选<font color=\"#D83220\">" + num + "</font>场"));
                }
            });
        }
        return mAdapter;
    }

    @Override
    protected void initInjector() {
        DaggerBasketballComponent.builder().basketballPresenterModule(new BasketballPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initData() {
        getAdapter().setDatas(null, mCurrentBetType);
        tv_selected.setText(Html.fromHtml("已选<font color=\"#D83220\">" + 0 + "</font>场"));
        String label = "";
        switch (mCurrentBetType) {
            case 0://胜负
                label = "sf";
                break;
            case 1://让分胜负
                label = "rfsf";
                break;
            case 2://胜分差
                label = "sfc";
                break;
            case 3://大小分
                label = "dxf";
                break;
            case 4://混合过关
            case 5://单关
                label = "hhgg";
                break;
        }
        mPresenter.getBasketballMatchList(label);
    }

    public void onResume() {
        super.onResume();
        getAdapter().notifyDataSetChanged();
    }

    @OnClick({R.id.img_back, R.id.ll_center, R.id.img_shaixuan, R.id.img_delete,
            R.id.tv_buy})
    public void onViewClicked(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_center:
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                } else {
                    img_xiala.setRotation(180);
                    initPopupWindowView();
                }
                break;
            case R.id.img_shaixuan:
                List<String> lids=getFilterLids();
                if(lids.isEmpty()){
                    return;
                }
                ArrayList<MatchFilterActivity.MatchFilter> matchFilters=new ArrayList<>();
                MatchFilterActivity.MatchFilter matchFilter;
                for(String str:lids){
                    matchFilter=new MatchFilterActivity.MatchFilter();
                    matchFilter.name=str;
                    if(mMatchFilters!=null){
                        matchFilter.isCheck=mMatchFilters.contains(str);
                    }
                    matchFilters.add(matchFilter);
                }
                Intent intent=new Intent(this, MatchFilterActivity.class);
                intent.putExtra("list",matchFilters);
                startActivityForResult(intent,1001);
            case R.id.img_delete:
                getAdapter().resetCheck();
                break;
            case R.id.tv_buy:
                List<List<BallMatchBo.MatchInfo>> list = getAdapter().getSelectMatchs();
                if (list == null || list.isEmpty()) {
                    T.showShort("请选择比赛！");
                    return;
                }


                if (list.size() == 1 && mCurrentBetType < 5) {
                    if (mCurrentBetType < 4) {
                        BallMatchBo.MatchInfo matchInfo = list.get(0).get(0);
                        if (!matchInfo.isDanguan()) {
                            T.showShort("至少选两场比赛！");
                            return;
                        }
                    } else {
                        boolean isCanDanguan = true;
                        List<BallMatchBo.MatchInfo> matchInfos = list.get(0);
                        for (BallMatchBo.MatchInfo matchInfo : matchInfos) {
                            if (matchInfo.getPlay().getCheckedNum() > 0 && !matchInfo.isDanguan()) {
                                isCanDanguan = false;
                                break;
                            }
                        }
                        if (!isCanDanguan) {
                            T.showShort("至少选两场比赛！");
                            return;
                        }
                    }
                }

                if (list.size() > 15) {
                    T.showShort("最多只能选15场比赛！");
                    return;
                }

                DataManager.getInstance().setTempObject(list);
                intent = new Intent(this, BasketballMatchCalculateMoneyActivity.class);
                intent.putExtra("current_type", mCurrentBetType);
                startActivity(intent);
                break;
        }
    }

    public ArrayList<String> getFilterLids() {
        ArrayList<String> listLids=new ArrayList<>();
        if (mDataList == null || mDataList.isEmpty()) {
            return listLids;
        }
        for (BallMatchBo bo : mDataList) {
            if (bo.getList() != null) {
                List<BallMatchBo.MatchInfo> list = bo.getList();
                for (BallMatchBo.MatchInfo matchInfo : list) {
                    if(!listLids.contains(matchInfo.getLid())) {
                        listLids.add(matchInfo.getLid());
                    }
                }
            } else if (bo.getList1() != null) {
                List<List<BallMatchBo.MatchInfo>> list = bo.getList1();
                for (List<BallMatchBo.MatchInfo> matchInfos : list) {
                    if(!listLids.contains(matchInfos.get(0).getPlay().getLid())) {
                        listLids.add(matchInfos.get(0).getPlay().getLid());
                    }
                }
            }
        }
        return listLids;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==1001 && resultCode==1002) {
            mMatchFilters = data.getExtras().getStringArrayList("list");
            if (mMatchFilters != null && !mMatchFilters.isEmpty() && mDataList!=null) {
                List<BallMatchBo> dataList= new ArrayList<>();
                BallMatchBo matchBo;
                for (BallMatchBo bo : mDataList) {
                    matchBo=new BallMatchBo();
                    matchBo.setDate(bo.getDate());
                    dataList.add(matchBo);
                    if (bo.getList() != null) {
                        List<BallMatchBo.MatchInfo> list = (List<BallMatchBo.MatchInfo>) ((ArrayList)bo.getList()).clone();
                        matchBo.setList(list);
                        for (int i=0;i<list.size();) {
                            if(!mMatchFilters.contains(list.get(i).getLid())) {
                                list.remove(i);
                                continue;
                            }
                            ++i;
                        }
                    } else if (bo.getList1() != null) {
                        List<List<BallMatchBo.MatchInfo>> list = (List<List<BallMatchBo.MatchInfo>>) ((ArrayList)bo.getList1()).clone();
                        matchBo.setList1(list);
                        for (int i=0;i<list.size();) {
                            if(!mMatchFilters.contains(list.get(i).get(0).getPlay().getLid())) {
                                list.remove(i);
                                continue;
                            }
                            ++i;
                        }
                    }
                }
                getAdapter().setDatas(dataList,mCurrentBetType);
            }else{
                getAdapter().setDatas(mDataList,mCurrentBetType);
            }
        }
    }

    public void initPopupWindowView() {
        LinearLayout contentView = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.popup_basketball_bet_type, null, false);
        mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.showAsDropDown(view_toolbar);
        // 设置背景半透明
        backgroundAlpha(0.7f);

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                img_xiala.setRotation(0);
                mPopupWindow = null;
            }
        });

        contentView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        resetBtnByCurrentBetType(contentView);
    }

    private void resetBtnByCurrentBetType(LinearLayout contentView) {
        int count = contentView.getChildCount();
        RadioGroup radioGroup;
        RadioButton btn;
        for (int i = 0; i < count; ++i) {
            radioGroup = (RadioGroup) contentView.getChildAt(i);
            for (int j = 0; j < 3; ++j) {
                int tag = i * 3 + j;
                btn = (RadioButton) radioGroup.getChildAt(j);
                btn.setTag(tag);
                btn.setChecked(tag == mCurrentBetType);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mCurrentBetType = (int) view.getTag();
                        mPopupWindow.dismiss();
                        mPopupWindow = null;
                        tv_title.setText(((RadioButton) view).getText());
                        initData();
                    }
                });
            }
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; // 0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void showBasketballMatchListSuccess(PageData<BallMatchBo> data) {
        if (data==null||data.getSchedules()==null) return;
        mDataList=(ArrayList<BallMatchBo>) data.getSchedules();
        mMatchFilters=null;
        getAdapter().setDatas(mDataList, mCurrentBetType);
        for (int i = 0; i < getAdapter().getGroupCount(); ++i) {
            list_view.expandGroup(i);
        }
    }

    @Override
    public void showBasketballMatchListSuccess2(PageData<BallMatchBo2> data) {
        if (data==null||data.getSchedules()==null) return;
        List<BallMatchBo> list = new ArrayList<>();
        if (data==null||data.getSchedules()==null) return;
        for (BallMatchBo2 bo2 : data.getSchedules()) {
            BallMatchBo bo = new BallMatchBo();
            for(List<BallMatchBo.MatchInfo> infos:bo2.getList()){
                resetDatas(infos);
            }
            bo.setList1(bo2.getList());
            bo.setDate(bo2.getDate());
            list.add(bo);
        }
        mDataList= (ArrayList<BallMatchBo>) list;
        mMatchFilters=null;
        getAdapter().setDatas(list, mCurrentBetType);
        for (int i = 0; i < getAdapter().getGroupCount(); ++i) {
            list_view.expandGroup(i);
        }
    }

    private void resetDatas(List<BallMatchBo.MatchInfo> list){
        boolean isHad;
        BallMatchBo.MatchInfo tempInfo=list.get(0);
        for(int i=1;i<5;++i){
            isHad=false;
            for(BallMatchBo.MatchInfo info:list){
                if(info.getType().equals(String.valueOf(i))){
                    isHad=true;
                    break;
                }
            }
            if(!isHad){
                BallMatchBo.MatchInfo matchInfo=new BallMatchBo.MatchInfo();
                matchInfo.setType(String.valueOf(i));
                matchInfo.setPlay(new BallMatchBo.MatchInfo());
                matchInfo.getPlay().setIssue(tempInfo.getPlay().getIssue());
                matchInfo.getPlay().setLid(tempInfo.getPlay().getLid());
                matchInfo.getPlay().setLn2(tempInfo.getPlay().getLn2());
                matchInfo.getPlay().setSaleCloseTime(tempInfo.getPlay().getSaleCloseTime());
                matchInfo.getPlay().setAn(tempInfo.getPlay().getAn());
                matchInfo.getPlay().setAn2(tempInfo.getPlay().getAn2());
                matchInfo.getPlay().setDt(tempInfo.getPlay().getDt());
                matchInfo.getPlay().setGameType("g");
                matchInfo.getPlay().setHand(tempInfo.getPlay().getHand());
                matchInfo.getPlay().setHand2(tempInfo.getPlay().getHand2());
                matchInfo.getPlay().setHn(tempInfo.getPlay().getHn());
                matchInfo.getPlay().setHn2(tempInfo.getPlay().getHn2());
                matchInfo.getPlay().setId(tempInfo.getPlay().getId());
                matchInfo.getPlay().setOt(tempInfo.getPlay().getOt());
                matchInfo.getPlay().setNo(tempInfo.getPlay().getNo());
                matchInfo.getPlay().setSpTypeDg(new ArrayList<>());
                matchInfo.getPlay().setSpTypeGg(new ArrayList<>());
                list.add(i-1,matchInfo);
            }
        }

    }

    @Override
    public void showBasketballMatchListError(String error) {
        T.showShort(error);
    }
}
